package com.m3958.firstgwt.client;


import java.util.logging.Level;
import java.util.logging.Logger;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.RootPanel;
import com.m3958.firstgwt.client.gin.FirstgwtGinjector;
import com.m3958.firstgwt.client.types.SmartResponseFieldName;
import com.m3958.gwtutil.clientside.client.utils.ServerSideUuid;
import com.smartgwt.client.data.DSRequest;
import com.smartgwt.client.data.DSResponse;
import com.smartgwt.client.data.Record;
import com.smartgwt.client.rpc.HandleErrorCallback;
import com.smartgwt.client.rpc.RPCManager;
import com.smartgwt.client.util.SC;

public class FirstGwt implements EntryPoint{
	
	public static String defaultToken = "e2/WELCOME";
	
	private final FirstgwtGinjector ginjector = GWT.create(FirstgwtGinjector.class);
	
    private Logger logger = Logger.getLogger("com.m3958.firstgwt");
    
//    private NativeUtils nu;
    
	@Override
	public void onModuleLoad() {
		ServerSideUuid ssuuid = ginjector.getServerSideUuid();
		ssuuid.fetchOnce();
//		nu = ginjector.getNativeUtils();
//		nu.addMessageClickListener();
//		DateUtil.setDefaultDisplayTimezone("0");
//		DateUtil.setAdjustForDST(false);
//		DateUtil.setDateParser(new DateParser() {
//			@Override
//			public Date parse(String dateString) {
//					GWT.log(dateString);
//			       final DateTimeFormat format = DateTimeFormat.getFormat("yyyy-MM-dd HH:mm");
//			       Date date = format.parse(dateString);
//			       return date;	
//			}
//		});
		RPCManager.setHandleErrorCallback(new HandleErrorCallback() {
			@Override
			public void handleError(DSResponse response, DSRequest request) {
				int code = 0;
				Record r = null; 
				if(response.getData().length > 0){
					r = response.getData()[0];
					code = r.getAttributeAsInt(SmartResponseFieldName.ERROR_CODE);
				}
				if(code != 0){
						String es = r.getAttributeAsString(SmartResponseFieldName.ERROR_MESSAGE);
						if(es.contains("Duplicate entry")){
							SC.warn("重复的记录！");
						}else{
							if(!es.isEmpty())SC.warn(es);
						}
				}
			}
		});
		startApp();
	}
	
	private void startApp(){
	    try {
	    	AppShell app = ginjector.getAppShell();
	    	app.draw();
	    	app.start();
	    	com.google.gwt.user.client.Element loading = DOM.getElementById("loadingWrapper");
	    	DOM.removeChild(RootPanel.getBodyElement(), loading);
	    	
	    }catch (Exception e) {
	    	logger.log(Level.SEVERE,"e:" + e);
	        e.printStackTrace();
	        String em = e.getMessage();
	        if(em != null){
	        	Window.alert(em);
	        }
		}
	}
}
